package com.fengxu.netty.dubborpc.netty;

import com.fengxu.netty.dubborpc.provder.HelloServerImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {

    // 初始化Netty服务器
    public static void startServer0(String hostname,int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new MyServerHandler());
                    }
                });
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(hostname, port).sync();
            channelFuture.addListener(future -> {
               if(future.isSuccess()){
                   System.out.println("绑定"+ hostname+":"+port+"成功!");
               } else {
                   System.out.println("服务器启动失败!");
               }
            });
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 自定义处理器
    private static class MyServerHandler extends SimpleChannelInboundHandler<String> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println("接收到客户端消息:"+msg);
            // 回调调用方法的消息必须以#大头如调用HelloServer.hello方法就是#HelloServer#hello#参数
            if(msg.startsWith("#HelloServer#hello")){
                String res =  new HelloServerImpl().hello(msg.substring(msg.lastIndexOf('#')+1));
                // 将结果返回给客户端
                ctx.writeAndFlush(res);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }
}
